async function getBooks() {
  const res = await axios.get("/api/books/");
  const htmlStr = res.data
    .map((item) => {
      const { author, bookname, publisher, id } = item;
      return `
          <tr>
            <th scope="row">${id}</th>
            <td>${bookname}</td>
            <td>${author}</td>
            <td>${publisher}</td>
            <td>
              <button type="button" data-id='${id}' class="btn btn-link btn-sm btn-delete">
                删除
              </button>
              <button type="button" data-id='${id}' class="btn btn-link btn-sm btn-update">
                编辑
              </button>
            </td>
          </tr>
      `;
    })
    .join("");
  document.querySelector("tbody").innerHTML = htmlStr;
}
getBooks();

const addModal = new bootstrap.Modal(document.getElementById("addModal"));
document.querySelector("#addBtn").addEventListener("click", async function () {
  const data = serialize(document.querySelector("#addForm"), {
    hash: true,
  });
  try {
    await axios.post("/api/books/", data);
    addModal.hide();
    document.querySelector("#addForm").reset();
    alert("添加成功!");
    getBooks();
  } catch (e) {
    if (e.response.status === 422) {
      alert("输入框不能为空!");
    }
  }
});

document.querySelector("tbody").addEventListener("click", async function (e) {
  if (e.target.classList.contains("btn-delete")) {
    const id = e.target.dataset.id;
    try {
      await axios.delete(`/api/books/${id}`);
      getBooks();
      alert("删除成功!");
    } catch (e) {
      if (e.response.status === 400) {
        alert("该图书已被其他管理员删除!");
        getBooks();
      }
    }
  }
});

const editModal = new bootstrap.Modal(document.getElementById("editModal"));
document.querySelector("tbody").addEventListener("click", async function (e) {
  if (e.target.classList.contains("btn-update")) {
    editModal.show();
    try {
      const id = e.target.dataset.id;
      const data = await axios.get(`/api/books/${id}`);
      for (let k in data.data) {
        document.querySelector(`#editForm [name=${k}]`).value = data.data[k];
      }
    } catch (e) {
      console.dir(e);
    }
  }
});
document.querySelector("#editBtn").addEventListener("click", async () => {
  const data = serialize(document.getElementById("editForm"), { hash: true });
  try {
    await axios.put(`/api/books/${data.id}`, data);
    editModal.hide();
    getBooks();
  } catch (e) {
    if (e.response.status === 422) {
        alert("输入框不能为空!");
      }
  }
});
